<template>
  <div class="list">
    <div style="width: 100%; height: 100%" id="mapContainer"></div>
    <!-- 底部遮罩 -->
    <div class="masks"></div>
    <div @click="loginOut" class="button">清除位置并退出</div>
    <iframe
      id="geoPage"
      width="0"
      height="0"
      frameborder="0"
      style="display: none"
      scrolling="no"
      src="https://apis.map.qq.com/tools/geolocation?key=WVRBZ-RMI6R-S46WU-WARXB-6V4WO-UWBIO&referer=myapp"
    >
    </iframe>
  </div>
</template>>
<script>
var wx = require("weixin-js-sdk");
// 以下代码为基于DOMOverlay实现聚合点气泡
function ClusterBubble(options) {
  TMap.DOMOverlay.call(this, options);
}

ClusterBubble.prototype = new TMap.DOMOverlay();

ClusterBubble.prototype.onInit = function (options) {
  this.iconList = options.iconList || [];
  this.content = options.content;
  this.position = options.position;
};

// 销毁时需要删除监听器
if (window.innerWidth < 1000) {
  ClusterBubble.prototype.onDestroy = function () {
    this.dom.removeEventListener("touchend", this.onClick);
    this.removeAllListeners();
  };
  ClusterBubble.prototype.onClick = function () {
    this.emit("touchend");
  };
} else {
  ClusterBubble.prototype.onDestroy = function () {
    this.dom.removeEventListener("click", this.onClick);
    this.removeAllListeners();
  };
  ClusterBubble.prototype.onClick = function () {
    this.emit("click");
  };
}

// 创建气泡DOM元素
ClusterBubble.prototype.createDOM = function () {
  var parentDiv = document.createElement("map-container");
  parentDiv.classList.add("custom-marker");
  // 添加contentDiv
  var contentDiv = document.createElement("div");
  if(this.iconList.length>2){
    contentDiv.classList.add("contentDiv2");
  }else{
    contentDiv.classList.add("contentDiv1");
  }

  // 添加角标
  var badge = document.createElement("div");
  badge.classList.add("badge");
  badge.innerText = this.content; // 设置角标上的数字
  // 添加图片
  var imgUrls = this.iconList; // 替换成你的图片URL
  imgUrls.forEach((item) => {
    var img = document.createElement("img");
    img.src = item.headImg;
    contentDiv.appendChild(img);
    img.classList.add("img");
  });
  parentDiv.appendChild(contentDiv);
  parentDiv.appendChild(badge);
  parentDiv.style.cssText = [
    "width: " + (40 + parseInt(this.content) * 2) + "px;",
    "height: " + (40 + parseInt(this.content) * 2) + "px;",
    "line-height: " + (40 + parseInt(this.content) * 2) + "px;",
  ].join(" ");

  // 监听点击事件，实现zoomOnClick
  this.onClick = this.onClick.bind(this);
  // pc端注册click事件，移动端注册touchend事件
  if (window.innerWidth < 1000) {
    parentDiv.addEventListener("touchend", this.onClick);
  } else {
    parentDiv.addEventListener("click", this.onClick);
  }
  return parentDiv;
};

ClusterBubble.prototype.updateDOM = function () {
  if (!this.map) {
    return;
  }
  // 经纬度坐标转容器像素坐标
  let pixel = this.map.projectToContainer(this.position);

  // 使文本框中心点对齐经纬度坐标点
  let left = pixel.getX() - this.dom.clientWidth / 2 + "px";
  let top = pixel.getY() - this.dom.clientHeight / 2 + "px";
  this.dom.style.transform = `translate(${left}, ${top})`;

  this.emit("dom_updated");
};

window.ClusterBubble = ClusterBubble;
export default {
  data() {
    return {
      logOutId:'',
      zoom: 11,
      geometriesData: [],
      map: null,
    };
  },
  async mounted() {
    // 1，初始化腾讯地图
    this.geolocation = new qq.maps.Geolocation(
      "WVRBZ-RMI6R-S46WU-WARXB-6V4WO-UWBIO", //KIVBZ-PBPRI-IQ3GI-5UZ5S-7BHEV-3VBFJ 久其
      "myapp"
    );
    // 2，并且开始定位
    this.getCurLocation();
  },
  created() {
    var param = window.location.href.split("?")[1];
    var query = this.parseQuery(param);
    this.userId = query.userId || "89BC199F028F4353A7787275D4837FB1";
    // console.log('----',query.userId)
  },
  methods: {
    // 获取小程序传入的参数
    parseQuery(query) {
      var reg = /([^=&\s]+)[=\s]*([^=&\s]*)/g;
      var obj = [];
      while (reg.exec(query)) {
        obj[RegExp.$1] = RegExp.$2;
      }
      return obj;
    },
    // 删除并退出
    loginOut(){
      let params = {
        id:this.logOutId
      }
      this.$http.Del("/api/member/associatorManage/anon/clearPosition",{params}).then(
          (res) => {
            this.$toast({
              msg: "清除成功",
              type: "success",
            });
            setTimeout(() => {
              wx.miniProgram.navigateTo({
              url:
                "/package/auth/pages/userHomepage/userHomepage?userId=" +
                this.logOutId,
            });
            }, 1500);
          },
          (error) => {}
        );
    },
    // 获取点数组
    havGeometriesData() {
      return new Promise((resolve, reject) => {
        let geometriesData = [];
        let params = {
          city: this.address|| "北京市",
          latitude: this.latitude  || 40.034326,
          longitude: this.longitude || 116.294169,
          userId:this.userId ||  '89BC199F028F4353A7787275D4837FB1'
        };
        this.$http.post("/api/member/associatorManage/anon/nearAlumni", params).then(
          (res) => {
            geometriesData = res.data;
            geometriesData.forEach(item=>{
              if(this.userId == item.userId){
                this.logOutId = item.id
              }
                item.position = new TMap.LatLng(
                  item.latitude,item.longitude
                )
            })
              // 模拟的数据
        // for (let i = 0; i < 20; i++) {
        //   if (i <= 10) {
        //     geometriesData.push({
        //       id: "demo1-" + i,
        //       styleId: "marker",
        //       position: new TMap.LatLng(
        //         this.latitude+ Math.random(0, 1) * i * 0.002,
        //         this.longitude + Math.random(0, 1) * i * 0.002
        //         // 22.316555+ Math.random(0, 1) * i * 0.002,
        //         // 114.174328 + Math.random(0, 1) * i * 0.002
        //       ),
        //       headImg: "https://huiyixing.dakabg.com/group1/M00/05/03/CgIlOmafd2qAU76DAAALQB5ZNEk21.jpeg",
        //       properties: {
        //         title: "marker" + i,
        //       },
        //     });
        //   } else {
        //     geometriesData.push({
        //       id: "demo1-" + i,
        //       styleId: "marker",
        //       position: new TMap.LatLng(
        //         this.latitude + Math.random(0, 1) * i * 0.002,
        //         this.longitude + Math.random(0, 1) * i * 0.002
        //       ),
        //       headImg: "https://huiyixing.dakabg.com/group1/M00/05/03/CgIlOmajH5SARJt_AAAB9n-YQE8627.png",
        //       properties: {
        //         title: "marker" + i,
        //       },
        //     });
        //   }
        // }
        console.log('geometriesData',geometriesData)
        resolve(geometriesData);
          },
          (error) => {}
        );
      
     
      });
    },
    getCurLocation() {
      this.geolocation.getLocation(this.showPosition, this.errorPosition); //开启定位
    },
    errorPosition(res) {
      console.log("定位失败", res);
    },
    async showPosition(position) {
      console.log("定位成功");
      this.longitude = position.lng;
      this.latitude = position.lat;
      this.address = position.city + position.province + position.addr;
      // alert(`${(position.lng, position.lat, position.addr)}`);
      console.log("定位成功", position);
      // 获取点数组
      this.geometriesData = await this.havGeometriesData();
      // 定位成功后开始绘制地图
      this.init();
    },
    init() {
      // lat lng中心点坐标
      let lat = this.latitude;
      let lng = this.longitude;
      var drawContainer = document.getElementById("mapContainer");
      var center = new TMap.LatLng(lat, lng); //设置中心点坐标
      this.map = new TMap.Map(drawContainer, {
        zoom: this.zoom,
        pitch: 0,
        pitchEnable: false,
        center: center,
        draggable: true,
        scrollable: true,
        viewMode: "2D",
        mapStyleId: "style 1",
      });

      setTimeout(() => {
        this.map.zoomTo(16);
      }, 3000);
      // 移除默认配置
      this.removeControl();
      // 创建点聚合实例
      this.createMarker();
    },
    // 创建点聚合实例
    createMarker() {
      let map = this.map;
      let geometriesData = this.geometriesData;
      // 标记点样式
      const markersStyle = {
        width: 30,
        height: 30,
        label: {
          borderRadius: 10,
          borderWidth: 4,
          borderColor: "#FFF",
          width: 30,
          height: 30,
          anchoX: -18,
          anchoY: -36,
        },
        anchor: { x: 17, y: 21 },
        color: "rgba(0, 0, 0, 0)", // 标注点文本颜色
        size: 22, // 标注点文本文字大小
        offset: { x: 0, y: -26 }, // 标注点文本文字基于direction方位的偏移属性
      };
      // 生成点标记的样式数据
      var MkStyles = {};
      geometriesData.forEach((item) => {
        MkStyles[item.id] = new TMap.MarkerStyle({
          ...markersStyle,
          src:
            item.headImg ||
            "https://huiyixing.dakabg.com/group1/M00/05/03/CgIlOmafd2qAU76DAAALQB5ZNEk21.jpeg",
        });
      });
      // 聚合物设置
      var markerCluster = new TMap.MarkerCluster({
        id: "cluster",
        map: map,
        enableDefaultStyle: false, // 启用默认样式
        minimumClusterSize: 2, // 形成聚合簇的最小个数
        geometries: geometriesData, //点数组
        zoomOnClick: true, // 点击簇时放大至簇内点分离
        gridSize: 60, // 聚合算法的可聚合距离
        averageCenter: false, // 每个聚和簇的中心是否应该是聚类中所有标记的平均值
        maxZoom: 16, // 采用聚合策略的最大缩放级别
      });
      var clusterBubbleList = [];
      var markerGeometries = [];
      var marker = null;
      // 监听聚合簇变化
      markerCluster.on("cluster_changed", function (e) {
        // 销毁旧聚合簇生成的覆盖物
        if (clusterBubbleList.length) {
          clusterBubbleList.forEach(function (item) {
            item.destroy();
          });
          clusterBubbleList = [];
        }
        markerGeometries = [];
        // 根据新的聚合簇数组生成新的覆盖物和点标记图层
        var clusters = markerCluster.getClusters();
        clusters.forEach(function (item) {
          if (item.geometries.length > 1) {
            let iconList = [];
            // 控制显示几个图标
            if (item.geometries.length == 1) {
              iconList = item.geometries.slice(0, 1);
            } else if (item.geometries.length == 2) {
              iconList = item.geometries.slice(0, 2);
            } else if (item.geometries.length == 3) {
              iconList = item.geometries.slice(0, 3);
            } else {
              iconList = item.geometries.slice(0, 4);
            }
            let clusterBubble = new ClusterBubble({
              map,
              position: item.center,
              content: item.geometries.length,
              iconList: iconList,
            });
            if (window.innerWidth < 1000) {
              clusterBubble.on("touchend", () => {
                map.fitBounds(item.bounds);
              });
            } else {
              clusterBubble.on("click", () => {
                map.fitBounds(item.bounds);
              });
            }
            clusterBubbleList.push(clusterBubble);
          } else {
            const data = item.geometries[0];
            markerGeometries.push({
              ...data,
              position: item.center,
              styleId: data.id,
            });
          }
        });
        if (marker) {
          // 已创建过点标记图层，直接更新数据
          marker.setGeometries(markerGeometries);
        } else {
          console.log("markerGeometries", markerGeometries);
          marker = new TMap.MultiMarker({
            map,
            styles: MkStyles,
            geometries: markerGeometries,
          });
          // 触发marker点击事件
          marker.on("click", (res) => {
            let userId = res.geometry.id
            console.log('--click--',res)
            wx.miniProgram.navigateTo({
              url:
                "/package/auth/pages/userHomepage/userHomepage?userId=" + userId,
            });
          });
        }
      });
    },
    // 移除默认的比例尺 指南针
    removeControl() {
      this.map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.SCALE); //移除腾讯地图比例尺
      this.map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ROTATION); //移除腾讯地图旋转控件
      //移除腾讯地图缩放控件
      this.map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ZOOM);
    },
  },
};
</script>
  
  <style scoped lang="less">
.list {
  height: 100%;
  width: 100%;
}
/deep/ .clusterBubble {
  border-radius: 50%;
  color: #fff;
  font-weight: 500;
  text-align: center;
  opacity: 0.88;
  background-image: linear-gradient(139deg, #4294ff 0%, #295bff 100%);
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.2);
  position: absolute;
  top: 0px;
  left: 0px;
  background-image: ;
}
.button {
  width: 80%;
  height: 40px;
  line-height: 40px;
  background-image: linear-gradient(139deg, #4294ff 0%, #295bff 100%);
  position: fixed;
  bottom: 40px;
  left: 0px;
  right: 0px;
  border-radius: 50px;
  color: #fff;
  z-index: 1000;
  margin-left: 10%;
  transition: all 0.12s ease-in-out;
  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.05);
  animation-fill-mode: both;
  animation: fadeInUp 0.6s ease-in-out;
}
.masks {
  width: 100%;
  height: 20%;
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 100;
  background-image: linear-gradient(180deg, transparent, #ffffff);
}
@keyframes fadeInUp {
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, 100%, 0);
    -ms-transform: translate3d(0, 100%, 0);
    transform: translate3d(0, 100%, 0);
  }
  100% {
    opacity: 1;
    -webkit-transform: none;
    -ms-transform: none;
    transform: none;
  }
}
/deep/.badge {
  position: absolute;
  top: -3px;
  right: 1px;
  width: 20px;
  height: 20px;
  background-color: red;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}
/deep/ .custom-marker {
  position: relative;
  width: 60px;
  height: 60px;
  background-color: #2196f3;
  border-radius: 50%;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  padding: 2px;
}
/deep/ .contentDiv1 {
  display: grid;
        grid-template-columns: repeat(2, 1fr);
        grid-template-rows: repeat(1, 1fr);
        gap: 1px;
  border-radius: 50%;
  position: relative;
  // display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
/deep/ .contentDiv2 {
  display: grid;
        grid-template-columns: repeat(2, 1fr);
        grid-template-rows: repeat(2, 1fr);
        gap: 1px;
  border-radius: 50%;
  position: relative;
  // display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
/deep/.custom-marker .img {
  width: 100%;
  height: 100%;
  // border-radius: 50%;
  // margin: 2px;
}
// /deep/.custom-marker .img3 {
//   width: 100%;
//   height: 100%;
//   // border-radius: 50%;
//   // margin: 2px;
// }
// /deep/.custom-marker .img4 {
//   width: 100%;
//   height: 100%;
//   // border-radius: 50%;
//   // margin: 2px;
// }
</style>
  